package net.xo68.destiny.starter.worker.handler.impl;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.report.JobHandleReplyDatagram;
import net.xo68.destiny.core.rocksdb.RocksDBStorage;
import net.xo68.destiny.starter.worker.SchedulerWorkerProperties;
import net.xo68.destiny.starter.worker.handler.JobHandleReplyFailStore;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任务处理状态回复失败信息存储 实现
 * @author wuxie
 * @version 2020-12-8
 */
@Slf4j
@Component
public class JobHandleReplyFailStoreImpl implements JobHandleReplyFailStore, SmartInitializingSingleton, DisposableBean {

    private final SchedulerWorkerProperties workerProperties;
    private final RocksDBStorage dbStorage;

    public JobHandleReplyFailStoreImpl(SchedulerWorkerProperties workerProperties) {
        this.workerProperties = workerProperties;
        this.dbStorage=new RocksDBStorage(workerProperties.replyPath()+"/fail",true,true);
    }

    @Override
    public List<JobHandleReplyDatagram> limit(long limit) {
        Map<String, JobHandleReplyDatagram> limitMap = dbStorage.limitString(limit);
        final List<JobHandleReplyDatagram> list=new ArrayList<>();
        limitMap.forEach((k,v)->{
            list.add(v);
        });
        return list;
    }

    @Override
    public void remove(final List<JobHandleReplyDatagram> eventList) {
        eventList.forEach(replyDatagram -> {
            dbStorage.remove(replyDatagram.getInstanceId()+"-"+replyDatagram.getSerialNumber());
        });
    }

    @Override
    public void batchAdd(final List<JobHandleReplyDatagram> eventList) {
        final Map<String,JobHandleReplyDatagram> datagramMap= new HashMap<>();
        eventList.forEach(replyDatagram -> {
            datagramMap.put(replyDatagram.getInstanceId()+"-"+replyDatagram.getSerialNumber(),replyDatagram);
        });
        dbStorage.putStringAll(datagramMap);
    }

    @Override
    public void destroy() throws Exception {
        log.debug("销毁 上报失败信息的rockdb");
        try {
            dbStorage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterSingletonsInstantiated() {
        log.debug("初始化rockdb");
        dbStorage.init();
    }
}
